package org.example.backend.config.filter;

import io.jsonwebtoken.Claims;
import org.example.backend.common.UserType;
import org.example.backend.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @author 啊昌
 * @date 2025/7/19 12:37
 * JwtAuthenticationFilter 拦截请求过滤器，拦截每一个http请求  在SecurityConfig注册一下过滤器
 */
@Component
public class JwtAuthenticationFilter  extends OncePerRequestFilter {
	@Autowired
	private JwtUtils jwtUtils;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		// 检查是否是不需要验证的路径
		String requestURI = request.getRequestURI();
//		  requestURI.contains("/doc.html") ||
		if(requestURI.contains("/auth") ||
		   requestURI.contains("/getCategory") ||
		   requestURI.contains("/getAllVideo") ||
		   requestURI.contains("/getBannerAll") ||
		   requestURI.contains("/webjars") ||
		   requestURI.contains("/v3/api-docs")){
			// 对于这些路径，直接放行
			filterChain.doFilter(request, response);
			return;
		}

		// 获取请求的token
		String authorization = request.getHeader("Authorization");

		// 验证JWT令牌
		if (StringUtils.hasText(authorization) && jwtUtils.validateToken(authorization)) {
			try {
				// 从token中获取用户ID
				Long userId = jwtUtils.getUserIdFromToken(authorization);
//				Claims claims = jwtUtils.parseToken(authorization);
//				Integer userType = claims.get("user_type", Integer.class);
//				String tp = null;
//				if(userType == UserType.USER_TYPE.getCode()){
//					tp = UserType.USER_TYPE.getIdentity();
//				}else {
//					tp = UserType.ADMIN_TYPE.getIdentity();
//				}
				// 创建认证对象
				UsernamePasswordAuthenticationToken authentication =
						new UsernamePasswordAuthenticationToken(
								userId,
								null,
								Collections.singletonList(new SimpleGrantedAuthority("tp"))
						);

				// 设置认证上下文
				SecurityContextHolder.getContext().setAuthentication(authentication);

				// 继续处理请求
				filterChain.doFilter(request, response);
			} catch (Exception e) {
				// 验证失败，清除认证上下文
				SecurityContextHolder.clearContext();
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				response.getWriter().write("Invalid token");
			}
		} else {
			// 没有token或token无效，清除认证上下文
			SecurityContextHolder.clearContext();
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			response.getWriter().write("Authentication required");
		}
	}
}
